using Microsoft.AspNetCore.Mvc;
using MVC作业.Models;

namespace MVC作业.Controllers;

public class StudentController : Controller
{
   
    public IActionResult Abc()
    {
        return View(11111111);
    }
    public IActionResult Find(string keyword)
    {
        dynamic data;
        if (string.IsNullOrEmpty(keyword))
        {
            data = Stus.StudentList;
        }
        else
        {
            data = Stus.StudentList.Where(item =>
                    {
                        return item.StudentName.Contains(keyword)
                        || item.Gender.Contains(keyword)
                        || (item.Avatar != null && item.Avatar.Contains(keyword))
                        || item.Birth.Contains(keyword);
                    });
        }

        var res = new
        {
            Code = 3000,
            data,
            msg = "查找成功"
        };
        return Json(res);
    }

    [HttpDelete]
    public IActionResult Del(int id)
    {
        dynamic obj;
    
        var tmp = Stus.StudentList.Find(item =>
        {
            return item.Id == id;
        });

        if (tmp != null)
        {
            
            Stus.StudentList.Remove(tmp);
           
            obj = new
            {
                Code = 3000,
                Data = new { Id = id, RemainStudent = Stus.StudentList },
                msg = "删除成功"
            };
        }
        else
        {

            obj = new
            {
                Code = 3000,
                Data = new { Id = id, RemainStudent = Stus.StudentList },
                msg = "删除失败"
            };
        }

        return Json(obj);
    }
     public IActionResult Edit(int id)
    {
        var stu = Stus.StudentList.FirstOrDefault(item =>
        {
            return item.Id == id;
        });
        return View(stu);
    }
    public IActionResult Save(int id, Students stu)
    {
        dynamic res;
        var student = Stus.StudentList.FirstOrDefault(item =>
        {
            return item.Id == id;
        });
        if (student != null)
        {
            student.StudentName = stu.StudentName;
            student.Birth = stu.Birth;
            student.Gender = stu.Gender;
            res = new
            {
                Code = 3000,
                Msg = "修改成功"
            };
        }
        else
        {
            Stus.StudentList.Add(stu);
            res = new
            {
                Code = 3000,
                Msg = "数据中未有此数据已为您添加"
            };
       }
       return Json(res);
    }
}

// public class UserModel
// {
//     [Required(ErrorMessage = "用户名不能为空")]
//     public string UserName { get; set; }

//     [RegularExpression(@"^[a-zA-Z0-9]{6,}$", ErrorMessage = "密码必须包含6个以上字符")]
//     public string Password { get; set; }

//     [Range(18, 65, ErrorMessage = "年龄必须在18到65之间")]
//     public int Age { get; set; }
// }